﻿ using BSWTradionWrapper;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Station.Inspect.SuaModel
{
    public class ModelBswTV : ModelBase
    {
        bswTraditionEvaluator model;
        public bool LoadModel(string fileName)
        {
            ClearModel();
            if (TryParseName(fileName) == false)
                return false;
            model = new bswTraditionEvaluator(fileName);
            if(model.status != TraStatus.Tra_Success)
            {
                ClearModel();
                return false;
            }
            return true;
        }

        void ClearModel()
        {
            if (model != null)
            {
                model.TraRelease();
                model = null;
            }
            minID = -1;
            maxID = -1;
        }

        public bool RunAsDefect(Bitmap img, int markID, int libID, double threshold, out List<BSW_DefectResultCS> res)
        {
            res = new List<BSW_DefectResultCS>();
            var curRes = new List<TraResult>();
            bool result = false;
            if(model !=null)
            {
                BitmapInfo bi = GetImagePixel(img);
                result = model.TraEvaluate(bi.Result, bi.width, bi.height, bi.Channels, bi.Stride, curRes);
            }
            if (model == null || result == false)
            {
                var defect = new BSW_DefectResultCS();
                defect.out_points = new List<PointF>();
                defect.out_points.Add(new PointF(2, 2));
                defect.out_points.Add(new PointF(img.Width-2, 2));
                defect.out_points.Add(new PointF(img.Width - 2, img.Height-2));
                defect.out_points.Add(new PointF(2, img.Height - 2));
                defect.score = 1;
                var tra = new TraResult();
                tra.defectResults = new List<BSW_DefectResultCS>();
                tra.defectResults.Add(defect);
            }
            foreach(var item in curRes)
            {
                if(item.defectResults !=null)
                {
                    res.AddRange(item.defectResults.Where(p => p.score >= threshold));
                }
            }
            return res.Count > 0;
        }
}
}
